import { ScrapeTask } from '../../shared/types'
import { logger } from '@roasmax/logger'
import { v4 as uuidv4 } from 'uuid'
import { useEntityManager } from '../storage/data-source'
import { Account, Task } from '../storage/entities'

export class TaskLifecycleManager {
  /**
   * 创建爬取任务
   */
  async createTask(taskData: Omit<ScrapeTask, 'id' | 'createdAt'>): Promise<ScrapeTask> {
    const task: ScrapeTask = {
      id: uuidv4(),
      ...taskData,
      createdAt: new Date()
    }

    await useEntityManager(async m => {
      const taskRepo = m.getRepository(Task)
      const taskEntity = Task.fromScrapeTask(task)
      await taskRepo.save(taskEntity)
    })
    logger.info('任务创建成功', { taskId: task.id })

    return task
  }

  /**
   * 获取所有任务
   */
  async getAllTasks(): Promise<ScrapeTask[]> {
    const taskEntities = await useEntityManager(async m => {
      const taskRepo = m.getRepository(Task)
      return await taskRepo.find()
    })
    return taskEntities.map(entity => entity.toScrapeTask())
  }

  /**
   * 根据ID获取任务
   */
  async getTaskById(taskId: string): Promise<ScrapeTask | null> {
    const taskEntity = await useEntityManager(async m => {
      const taskRepo = m.getRepository(Task)
      return await taskRepo.findOne({ where: { id: taskId } })
    })
    return taskEntity ? taskEntity.toScrapeTask() : null
  }

  /**
   * 更新任务状态
   */
  async updateTaskStatus(taskId: string, status: string, completedAt?: Date, result?: any): Promise<void> {
    await useEntityManager(async m => {
      const taskRepo = m.getRepository(Task)
      const taskEntity = await taskRepo.findOne({ where: { id: taskId } })
      
      if (taskEntity) {
        const task = taskEntity.toScrapeTask()
        task.status = status as any;
        if (completedAt) {
          task.completedAt = completedAt
        }
        if (result) {
          task.result = result
        }
        
        const updatedTaskEntity = Task.fromScrapeTask(task)
        await taskRepo.save(updatedTaskEntity)
      }
    })
  }

  /**
   * 获取账号信息
   */
  async getAccountById(accountId: string): Promise<any | null> {
    const account = await useEntityManager(async m => {
      const accountRepo = m.getRepository(Account)
      return await accountRepo.findOne({ where: { id: parseInt(accountId) } })
    })
    return account
  }

  /**
   * 导出任务数据
   */
  async exportTaskData(taskId: string, format: 'json' | 'csv'): Promise<string> {
    logger.info('导出任务数据', { taskId, format })

    const task = await this.getTaskById(taskId)
    if (!task) {
      throw new Error('任务不存在')
    }

    if (task.status !== 'completed') {
      throw new Error('只能导出已完成的任务数据')
    }

    // 简化的导出实现
    const exportPath = `./exports/${taskId}.${format}`

    if (format === 'json') {
      // 导出JSON格式
      const data = {
        task: task,
        exportTime: new Date().toISOString(),
        data: [] // 这里应该是实际的爬取数据
      }

      // 实际应用中应该写入文件系统
      logger.info('JSON数据导出完成', { exportPath })
    } else if (format === 'csv') {
      // 导出CSV格式
      logger.info('CSV数据导出完成', { exportPath })
    }

    return exportPath
  }

  /**
   * 获取统计信息
   */
  async getStats(): Promise<{
    totalTasks: number
    completedTasks: number
    totalData: number
  }> {
    // 降低日志级别，避免频繁输出
    logger.debug('获取统计信息')

    const allTasks = await this.getAllTasks()
    const completedTasks = allTasks.filter(task => task.status === 'completed')

    // 从数据库获取实际的微博数据统计
    const weiboStats = await useEntityManager(async m => {
      const weiboRepo = m.getRepository('WeiboData')
      const totalCount = await weiboRepo.count()
      return { totalCount }
    })

    return {
      totalTasks: allTasks.length,
      completedTasks: completedTasks.length,
      totalData: weiboStats.totalCount
    }
  }
}
